package com.ideafactory.client.utils.versioncontrol;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.widget.ProgressBar;

import com.ideafactory.client.utils.FileConstants;
import com.ideafactory.client.utils.VersionUpdateConstants;
import com.ideafactory.client.utils.netutils.MyCallBack;
import com.ideafactory.client.utils.netutils.NetUtils;
import com.ideafactory.client.ybservice.xmpphandler.ResourceUpdate;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class UpdateManager {

    private Context mContext;

    //返回的安装包url
    public static String apkUrl = "http://211.157.160.102/imgserver/hsd.apk";

    /* 下载包安装路径 */
    public static final String savePath = FileConstants.IMAGE_CACHE_PATH;

    public static final String saveFileName = savePath + "hsd.apk";

    /* 进度条与通知ui刷新的handler和msg常量 */
    private ProgressBar mProgress;

    private static final int DOWN_UPDATE = 1;

    private static final int DOWN_OVER = 2;

    private int progress;

    private Thread downLoadThread;

    private boolean interceptFlag = false;

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DOWN_UPDATE:
                    break;
                case DOWN_OVER:
                    installApk();
                    break;
                default:
                    break;
            }
        }
    };

    public UpdateManager(Context context) {
        this.mContext = context;
    }

    //	//外部接口让主Activity调用
    public void checkUpdateInfo(String version) {
        Map paramMap = new HashMap();
        paramMap.put("clientVersion", version);
        paramMap.put("type", VersionUpdateConstants.CURRENT_VERSION + "");
        NetUtils.Post(ResourceUpdate.VERSION_URL, paramMap, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                handResut(result);
            }
        });
    }

    private void handResut(String result){
        if (result.startsWith("\"")) {
            result = result.substring(1, result.length()-1);
        }
        if (result.endsWith("\"")) {
            result = result.substring(0, result.length()-2);
        }
        if (result.equals("1")) {
            //不需要更新
        } else {
            apkUrl = result;
            //下载apk
            downloadApk();
            //showNoticeDialog();
        }
    }

    private Runnable mdownApkRunnable = new Runnable() {
        @Override
        public void run() {
            try {
                URL url = new URL(apkUrl);

                HttpURLConnection conn = (HttpURLConnection) url.openConnection();

                conn.setConnectTimeout(30000);
                conn.setReadTimeout(360000);

                conn.connect();
                int length = conn.getContentLength();
                InputStream is = conn.getInputStream();

                File file = new File(savePath);
                if (!file.exists()) {
                    file.mkdir();
                }

                String apkFile = saveFileName;
                File ApkFile = new File(apkFile);
                FileOutputStream fos = new FileOutputStream(ApkFile);

                int count = 0;
                byte buf[] = new byte[1024];

                do {
                    int numread = is.read(buf);
                    count += numread;
                    progress = (int) (((float) count / length) * 100);
                    //更新进度
                    mHandler.sendEmptyMessage(DOWN_UPDATE);
                    if (numread <= 0) {
                        //下载完成通知安装
                        mHandler.sendEmptyMessage(DOWN_OVER);
                        break;
                    }
                    fos.write(buf, 0, numread);

                } while (!interceptFlag);//点击取消就停止下载.

                fos.close();
                is.close();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    };

    /**
     * 下载apk
     * @param
     */
    public void downloadApk() {
        downLoadThread = new Thread(mdownApkRunnable);
        downLoadThread.start();
    }

    /**
     * 安装apk
     * @param
     */
    public void installApk() {
        File apkfile = new File(saveFileName);
        if (!apkfile.exists()) {
            return;
        }
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(apkfile), "application/vnd.android.package-archive");
        mContext.startActivity(intent);
    }
}
